
Page({

  data: {
    bookInfo: "",                                    //装载index中传递过来的参数，其为书籍信息
    img: '',
    array: ["科研文档", "参赛资料", "人文科学", "编程语言", "互联网", "IT技术"],
    index: 0,
    numarray: ["0","1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"],
    numindex: 1, 

    date: '2018-12-20',

    owner: [],
    ownerid: [],
    rentdate: [],
    renew: []
  },

  //picker选择器
  bindPickerChange: function (e) {
    // console.log('picker 值为:', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },

  //日期选择
  bindDateChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      date: e.detail.value
    }) 
  },

  //数量选择
  numPickerChange: function (e) {
    console.log('picker 值为:', e.detail.value)
    this.setData({
      numindex: e.detail.value
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.setData({                                  //将传递来的json字符串序列化为Json格式
      bookInfo: JSON.parse(options.value)           //然后将值赋给bookInfo
    })
    // console.log(JSON.parse(options.value))       //检验传递过来的参数
    // console.log(this.data.bookInfo)
  },

  //表单提交至云数据库
  formSubmit: function (e) {
    var that = this;
    var formData = e.detail.value;

    wx.cloud.init({ env: getApp().globalData.myenv })                      //云开发初始化
    const db = wx.cloud.database({ env: getApp().globalData.myenv })       //数据库初始化

    //为已借书籍展示做准备
    var tempBooknum = this.data.numarray[this.data.numindex]
    for (let i = 0; i < tempBooknum; i++) {
      this.data.owner[i] = '无人',
      this.data.ownerid[i] = '空'
      this.data.rentdate[i] = 0
      this.data.renew[i] = false
    }

    db.collection('Books').add({                                  //在集合上新增记录
      data: {                                                     // data 字段表示需新增的 JSON 数据
        title: formData.title,
        author: formData.author,
        publisher: formData.publisher,
        btype: this.data.array[this.data.index],
        pubdate: new Date(this.data.date),
        bookNum: this.data.numarray[this.data.numindex],
        summary: formData.summary,
        image: this.data.img,
        qrCode: false,
        collectionStatus: false,
        collectionNum: 0,
        owner: this.data.owner,
        ownerid: this.data.ownerid,
        rentdate: this.data.rentdate,
        rentrecord: 0,
        bookava: 0,
        renew: this.data.renew

      },

      success: function (res) {
        console.log('add success:', res)
        //内置显示信息提示框函数
        wx.showToast({
          title: '成功',
          icon: 'success',
          duration: 1000          //提示的延迟时间
        })

        setTimeout(function () {
          wx.redirectTo({                                   //页面无参数传递跳转
            url: '../desktop/desktop',
          })
        }, 1000) //延迟时间 这里是2秒

      },


      //接口调用失败
      fail: (res) => {
        console.error
        wx.showToast({
          title: '失败',
          icon: 'success',
          duration: 1000
        }),

          setTimeout(function () {
          wx.redirectTo({                                   //页面无参数传递跳转
              url: '../desktop/desktop',
            })
          }, 1000) //延迟时间 这里是2秒

      }


    })

    // console.log('form发生了submit事件，携带数据为：', e.detail.value)
  },

  //拍照上传图片函数
  imgHandle: function () {
    var that = this;
    wx.chooseImage({
      count: 1,                                       //可选图片的数量，最多9张
      sizeType: ['original', 'compressed'],           //所选图片的尺寸
      sourceType: ['album', 'camera'],                //图片来源

      success: chooseResult => {
        //获取当前时间戳
        var timestamp = Date.parse(new Date());
        timestamp = timestamp / 1000;
        console.log('chooseResult.tempFilePaths[0]:',chooseResult.tempFilePaths[0])
        wx.cloud.init(),
          // 将图片上传至云存储空间
          wx.cloud.uploadFile({
            // 指定上传到的云路径
            cloudPath: 'book' + timestamp + '.jpg',
            // 指定要上传的文件的小程序临时文件路径
            filePath: chooseResult.tempFilePaths[0],
            // 成功回调
            success: res => {
              console.log('上传成功', res)
              that.setData({ img: res.fileID })
            }
          })
      },



    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})